package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.mapper.UserFollowMapper;
import com.fzfnn.scrapbook.service.UserFollowService;
import com.fzfnn.scrapbook.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private RedisTemplate<String, String> redisMail;

    @Override
    public R followUser(String token, int followedId) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        int followerId = Integer.parseInt(userId);
        if (followerId == followedId) {
            return R.errorMsg("不能关注自己");
        }
        if (userFollowMapper.checkFollow(followerId, followedId) != null) {
            return R.errorMsg("你已关注该用户");
        }
        userFollowMapper.insertFollow(followerId, followedId);
        return R.successMsg("关注成功");
    }

    @Override
    public R unfollowUser(String token, int followedId) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        int followerId = Integer.parseInt(userId);
        int affected = userFollowMapper.deleteFollow(followerId, followedId);
        return affected > 0 ? R.successMsg("取消关注成功") : R.errorMsg("取消失败或未关注");
    }

    @Override
    public R getFollowedUserIds(String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            R.errorMsg("登录信息无效");
        }
        int followerId = Integer.parseInt(userId);
        List<Integer> followedIds = userFollowMapper.getFollowedIds(followerId);
        List<Map<String, Object>> userInfoList = userFollowMapper.getFollowedInfoByIds(followedIds);
        return R.successData(userInfoList);
    }

    @Override
    public R getFollowerIds(String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            R.errorMsg("登录信息无效");
        }

        return R.successData(userFollowMapper.getFollowerFanInfo(Integer.parseInt(userId)));
    }
    @Override
    public R getFollowedJournals(String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            R.errorMsg("登录信息无效");
        }
        return R.successData(userFollowMapper.getFollowedJournals(Integer.parseInt(userId)));
    }
}
